<template>
  <view class="container">
    <!-- 地址 -->
    <navigator url="/pages/address/address?source=1" class="address-section">
      <view class="order-content">
        <text class="yticon icon-shouhuodizhi"></text>
        <view class="cen">
          <view class="top">
            <text class="name">{{ addressData.name }}</text>
            <text class="mobile">{{ addressData.mobile }}</text>
          </view>
          <text class="address">{{ addressData.address }}</text>
        </view>
        <text class="yticon icon-you"></text>
      </view>
    </navigator>

    <!-- 商品信息 -->
    <view class="order-info">
      <text class="title">确认订单</text>
      <view class="product-item" v-for="product in goodsData" :key="index">
        <image :src="product.image" mode="aspectFill"></image>
        <view class="product-details">
          <text class="product-name">{{ product.name }}</text>
          <text class="product-price">￥{{ product.price }}</text>
          <text class="quantity">数量：{{ product.quantity }}</text>
        </view>
      </view>
    </view>

    <!-- 底部栏 -->
    <view class="bottom-bar">
      <view class="btn-confirm">
        <text>实付款</text>
        <text class="price-tip">￥</text>
        <text class="price">{{ totalMoney }}</text>
      </view>
      <button class="btn-confirm2" @click="confirmOrder">提交订单</button>
    </view>
  </view>
</template>

<script>
import product from "@/pages/product/product.vue";

// 订单创建页面逻辑
export default {
  data() {
    return {
      goodsData: [], // 接收到的购物车商品数据
      totalMoney: 0, // 总金额
      addressData: {}, // 地址信息
    };
  },
  onLoad(options) {
    // 解析传递过来的购物车数据
    if (options.data) {
      const goodsDataString = decodeURIComponent(options.data); // 解码
      this.goodsData = JSON.parse(goodsDataString); // 解析为对象
      console.log("接收到的 goodsData:", this.goodsData);
    }
    this.calculateTotalMoney()
    this.getAddressData()
  },
  methods: {
    calculateTotalMoney() {
      // 计算总金额
      this.totalMoney = this.goodsData.reduce((total, product) => {
        return total + product.price * product.quantity;
      }, 0);
      console.log("订单商品信息:",this.goodsData)
      console.log("总金额：",this.totalMoney)
    },
    getAddressData() {
      // 获取地址信息（示例）
      this.addressData = {
        name: '许小星',
        mobile: '13853989563',
        address: '山东省济南市历城区金九大道149号',
      };
      console.log("购物车传过来的数据data:",data)
      console.log("购物车传过来的数据:",this.goodsData)
    },
    //跳转支付页面
    async confirmOrder() {
      try {
        // 提交订单，批量删除 Redis 中的购物车商品
        await this.deleteCartItems(this.goodsData); // 调用批量删除方法
        console.log("库存充足时 goods 数据：", this.goodsData);

        const userInfo = uni.getStorageSync('userInfo'); // 获取当前用户的 ID

        // 调用后端接口创建订单
        const res = await uni.request({
          url: 'http://localhost:8080/app/shop/order',
          method: 'POST',
          data: {
            totalFee: this.totalMoney,
            paymentType: 1,   //只用支付宝
            userId: userInfo.id,
            shopAddressId: 1,
            shopOrderDetailList: this.goodsData.map((item) => ({
              name: item.name,
              itemId: item.id,
              num: item.quantity,
              price: item.price,
            })),
          },
        });

        const orderId = res[1].data.data; // 获取订单ID号
        const totalFee = this.totalMoney
        console.log('获取订单ID：', orderId);

        uni.showToast({
          title: '下单成功',
          icon: 'success',
        });

        // 跳转到支付页面，并传递订单ID
        uni.redirectTo({
          url: `/pages/money/pay?orderId=${orderId}&totalFee=${totalFee}`,
        });
      } catch (error) {
        uni.showToast({
          title: '下单失败',
          icon: 'none',
        });
      }
    },
    // 批量删除购物车商品
    async deleteCartItems(goodsData) {
      const userId = uni.getStorageSync('token'); // 获取用户 ID
      const itemIds = goodsData.map(item => item.id); // 获取选中的商品 ID 列表

      try {
        const result = await uni.request({
          url: 'http://localhost:8080/app/api/cart/deleteBatch', // 后端批量删除接口
          method: 'POST',
          data: {
            userId: userId,
            itemIds: itemIds // 商品 ID 列表
          },
        });

        if (result[1].statusCode === 200) {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          });
          return true;
        } else {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
          return false;
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        console.error("删除购物车商品失败：", error);
        return false;
      }
    }
  },
};
</script>

<style scoped>

.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.product-item image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 28rpx;
  font-weight: bold;
}

.product-price {
  font-size: 24rpx;
  color: #ff5000;
}

.quantity {
  font-size: 24rpx;
  color: #666;
}

.container {
  padding: 20rpx;
}
.address-section {
  padding: 30upx 0;
  background: #fff;
  position: relative;

  .order-content {
    display: flex;
    align-items: center;
  }

  .icon-shouhuodizhi {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 90upx;
    color: #888;
    font-size: 44upx;
  }

  .cen {
    display: flex;
    flex-direction: column;
    flex: 1;
    font-size: 28upx;
    color: $font-color-dark;
  }

  .name {
    font-size: 34upx;
    margin-right: 24upx;
  }

  .address {
    margin-top: 16upx;
    margin-right: 20upx;
    color: $font-color-light;
  }

  .icon-you {
    font-size: 32upx;
    color: $font-color-light;
    margin-right: 30upx;
  }

  .a-bg {
    position: absolute;
    left: 0;
    bottom: 0;
    display: block;
    width: 100%;
    height: 5upx;
  }
}

.order-info {
  margin-bottom: 120rpx;
}

.title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

//.product-item {
//  display: flex;
//  align-items: center;
//  margin-bottom: 20rpx;
//}

//.product-item image {
//  width: 200rpx;
//  height: 200rpx;
//  border-radius: 10rpx;
//  margin-right: 20rpx;
//}

//.product-details {
//  flex: 1;
//}

//.product-name {
//  font-size: 28rpx;
//  font-weight: bold;
//}

//.product-price {
//  font-size: 24rpx;
//  color: #ff5000;
//}

//.quantity {
//  font-size: 24rpx;
//  color: #666;
//}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1rpx solid #eee;
}

.btn-confirm {
  width: 40%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #ff8800;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}
.btn-confirm2 {
  width: 60%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #007aff;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}
.a-bg {
  position: absolute;
  left: 0;
  bottom: 0;
  display: block;
  width: 100%;
  height: 5upx;
}

</style>
